<template>
  <view class="address-edit">
    <!-- 导航栏 -->
    <NavBar :title="isEdit ? '编辑地址' : '新增地址'" />

    <!-- 地址表单 -->
    <view class="form-container">
      <nut-form>
        <nut-form-item label="收货人" required>
          <nut-input v-model="addressForm.name" placeholder="请输入收货人姓名" />
        </nut-form-item>
        
        <nut-form-item label="手机号码" required>
          <nut-input v-model="addressForm.phone" placeholder="请输入手机号码" type="tel" />
        </nut-form-item>
        
        <nut-form-item label="所在地区" required>
          <nut-cell @click="showAreaPicker = true">
            <template #desc>
              <view class="area-value">
                {{ addressForm.province && addressForm.city ? 
                  `${addressForm.province} ${addressForm.city} ${addressForm.district || ''}` : 
                  '请选择所在地区' }}
              </view>
            </template>
          </nut-cell>
        </nut-form-item>
        
        <nut-form-item label="详细地址" required>
          <nut-textarea 
            v-model="addressForm.addressDetail" 
            placeholder="请输入详细地址信息，如街道、门牌号等"
            :max-length="100"
          />
        </nut-form-item>
        
        <nut-form-item label="设为默认地址">
          <nut-switch v-model="addressForm.isDefault" />
        </nut-form-item>
      </nut-form>
    </view>

    <!-- 微信一键导入地址 -->
    <view class="wx-address" v-if="!isEdit">
      <nut-cell title="一键获取微信收货地址" is-link @click="getWxAddress" />
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-button">
      <nut-button type="primary" block @click="saveAddress">保存</nut-button>
      <nut-button v-if="isEdit" type="danger" block @click="showDeleteConfirm">删除</nut-button>
    </view>

    <!-- 地区选择器 -->
    <nut-picker
      v-model:visible="showAreaPicker"
      :columns="areaColumns"
      title="选择地区"
      @confirm="onAreaConfirm"
    />

    <!-- 删除确认弹窗 -->
    <nut-dialog
      title="提示"
      content="确定要删除该收货地址吗？"
      v-model:visible="showDeleteDialog"
      @cancel="showDeleteDialog = false"
      @ok="deleteAddress"
    />
  </view>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import Taro from '@tarojs/taro'
import NavBar from '@/components/NavBar/index.vue'
import userApi from '@/api/user'

// 获取路由参数
const router = Taro.getCurrentInstance().router
const addressId = router?.params?.id
const isEdit = ref(!!addressId)

// 地址表单
const addressForm = reactive({
  id: '',
  name: '',
  phone: '',
  province: '',
  city: '',
  district: '',
  addressDetail: '',
  isDefault: false
})

// 地区选择器
const showAreaPicker = ref(false)
const areaColumns = ref([
  // 实际项目中应该从API获取省市区数据
  // 这里使用简化的示例数据
  {
    values: ['北京市', '上海市', '广东省', '江苏省', '浙江省', '四川省'],
    defaultIndex: 0
  },
  {
    values: ['北京市', '上海市', '广州市', '深圳市', '南京市', '杭州市', '成都市'],
    defaultIndex: 0
  },
  {
    values: ['东城区', '西城区', '朝阳区', '海淀区', '福田区', '南山区', '姑苏区'],
    defaultIndex: 0
  }
])

// 删除确认弹窗
const showDeleteDialog = ref(false)

// 获取地址详情
const getAddressDetail = async () => {
  if (!addressId) return
  
  try {
    Taro.showLoading({ title: '加载中' })
    
    // 实际项目中应该调用API获取地址详情
    // const res = await userApi.getAddressDetail(addressId)
    // if (res.code === 0 && res.data) {
    //   Object.assign(addressForm, res.data)
    // }
    
    // 模拟数据
    setTimeout(() => {
      Object.assign(addressForm, {
        id: addressId,
        name: '张三',
        phone: '13800138000',
        province: '广东省',
        city: '深圳市',
        district: '南山区',
        addressDetail: '科技园南路XX号XX大厦',
        isDefault: true
      })
      Taro.hideLoading()
    }, 500)
  } catch (error) {
    console.error('获取地址详情失败', error)
    Taro.showToast({
      title: '获取地址详情失败',
      icon: 'none'
    })
    Taro.hideLoading()
  }
}

// 保存地址
const saveAddress = async () => {
  // 表单验证
  if (!addressForm.name) {
    return Taro.showToast({
      title: '请输入收货人姓名',
      icon: 'none'
    })
  }
  
  if (!addressForm.phone) {
    return Taro.showToast({
      title: '请输入手机号码',
      icon: 'none'
    })
  }
  
  // 简单的手机号验证
  const phoneReg = /^1[3-9]\d{9}$/
  if (!phoneReg.test(addressForm.phone)) {
    return Taro.showToast({
      title: '手机号格式不正确',
      icon: 'none'
    })
  }
  
  if (!addressForm.province || !addressForm.city) {
    return Taro.showToast({
      title: '请选择所在地区',
      icon: 'none'
    })
  }
  
  if (!addressForm.addressDetail) {
    return Taro.showToast({
      title: '请输入详细地址',
      icon: 'none'
    })
  }
  
  try {
    Taro.showLoading({ title: '保存中' })
    
    // 实际项目中应该调用API保存地址
    // const api = isEdit.value ? userApi.updateAddress : userApi.addAddress
    // const res = await api(addressForm)
    // if (res.code === 0) {
    //   Taro.showToast({
    //     title: '保存成功',
    //     icon: 'success'
    //   })
    //   setTimeout(() => {
    //     Taro.navigateBack()
    //   }, 1500)
    // }
    
    // 模拟保存成功
    setTimeout(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '保存成功',
        icon: 'success'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }, 1000)
  } catch (error) {
    console.error('保存地址失败', error)
    Taro.showToast({
      title: '保存失败',
      icon: 'none'
    })
    Taro.hideLoading()
  }
}

// 删除地址
const showDeleteConfirm = () => {
  showDeleteDialog.value = true
}

const deleteAddress = async () => {
  try {
    Taro.showLoading({ title: '删除中' })
    
    // 实际项目中应该调用API删除地址
    // const res = await userApi.deleteAddress(addressForm.id)
    // if (res.code === 0) {
    //   Taro.showToast({
    //     title: '删除成功',
    //     icon: 'success'
    //   })
    //   setTimeout(() => {
    //     Taro.navigateBack()
    //   }, 1500)
    // }
    
    // 模拟删除成功
    setTimeout(() => {
      Taro.hideLoading()
      Taro.showToast({
        title: '删除成功',
        icon: 'success'
      })
      setTimeout(() => {
        Taro.navigateBack()
      }, 1500)
    }, 1000)
  } catch (error) {
    console.error('删除地址失败', error)
    Taro.showToast({
      title: '删除失败',
      icon: 'none'
    })
    Taro.hideLoading()
  }
}

// 地区选择确认
const onAreaConfirm = (values) => {
  addressForm.province = values[0]
  addressForm.city = values[1]
  addressForm.district = values[2] || ''
}

// 获取微信收货地址
const getWxAddress = () => {
  Taro.chooseAddress({
    success: (res) => {
      addressForm.name = res.userName
      addressForm.phone = res.telNumber
      addressForm.province = res.provinceName
      addressForm.city = res.cityName
      addressForm.district = res.countyName
      addressForm.addressDetail = res.detailInfo
    },
    fail: (err) => {
      console.error('获取微信地址失败', err)
      if (err.errMsg.indexOf('auth deny') >= 0) {
        Taro.showModal({
          title: '提示',
          content: '请在小程序设置中打开"通讯地址"权限'
        })
      }
    }
  })
}

// 组件挂载时初始化
onMounted(() => {
  if (isEdit.value) {
    getAddressDetail()
  }
})
</script>

<style lang="scss" scoped>
.address-edit {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 100px;
  
  .form-container {
    margin: 10px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .wx-address {
    margin: 10px;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
  }
  
  .area-value {
    color: #666;
  }
  
  .bottom-button {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 10px 15px;
    background-color: #fff;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.05);
    z-index: 10;
    display: flex;
    flex-direction: column;
    gap: 10px;
  }
}
</style>